package com.yx.cloud.network.ap;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.iot.common.utils.LogUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeoutException;

/**
 * 网络操作类.
 */
public class WifiNetUtil {
    /**
     * http链接
     */
    private HttpURLConnection mConnection;
    /**
     * 输出流
     */
    private DataOutputStream dos;
    private BufferedReader reader;

    public String sendPost(String path, String attribute, Network network, int connect_timeout, int so_timeout) throws IOException, TimeoutException {
        URL url = new URL(path);
        if (network != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                mConnection = (HttpURLConnection) network.openConnection(url);
            } catch (Exception e) {
                //如果发生异常,还是尝试原始方案
            }
        }
        if (mConnection == null) {
            mConnection = (HttpURLConnection) url.openConnection();
        }
        mConnection.setDoOutput(true); // 设置输出,post请求必须设置.
        mConnection.setDoInput(true); // 设置输入,post请求必须设置.
        mConnection.setUseCaches(false); // 设置是否启用缓存,post请求不能使用缓存.
        // 设置Content-Type属性.
        mConnection.setRequestProperty("Content-Type", "application/json");
        mConnection.setConnectTimeout(connect_timeout);
        mConnection.setReadTimeout(so_timeout);
        mConnection.setRequestMethod("POST");
        mConnection.connect(); // 打开网络链接.
        dos = new DataOutputStream(mConnection.getOutputStream());
        if (!TextUtils.isEmpty(attribute)) {
            dos.write(attribute.getBytes("UTF-8")); // 将请求参数写入网络链接.
        }
        dos.flush();
        return readResponse();
    }

    /**
     * 做了特殊处理
     */
    private String readResponse() throws IOException {
        String result = null;
        try {
            int code = mConnection.getResponseCode();
            mConnection.getContentLength();
            if (HttpURLConnection.HTTP_OK <= code && code <= 210) { // 若响应码以2开头则读取响应头总的返回信息
                result = inputStream2String(mConnection.getInputStream());
            }
            closeConnection();
            return result != null ? result : "error";
        } catch (IOException e) {//机器人可能收到post立即关闭了wifi,同视为操作成功
            e.printStackTrace();
            closeConnection();
            return "";
        }
    }

    private String inputStream2String(InputStream inputStream) throws IOException {
        StringBuilder builder = new StringBuilder();
        String line;
        reader = new BufferedReader(new InputStreamReader(inputStream));
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
    }

    private void closeConnection() {
        try {
            reader.close();
            dos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (mConnection != null) {
            mConnection.disconnect();
        }
    }

    /**
     * true if mobile data is enabled
     *
     * @return
     */
    public static boolean isMobileEnable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        }
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        return !((info == null) || (!info.isAvailable())) && info.getType() == ConnectivityManager.TYPE_MOBILE;
    }

    /**
     * 移动网络开关
     */
    public static boolean setMobileDataEnabled(Context context, boolean enabled) {
        final TelephonyManager mTelManager;
        mTelManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        try {
            Method m = mTelManager.getClass().getDeclaredMethod("getITelephony");
            m.setAccessible(true);
            Object telephony = m.invoke(mTelManager);
            m = telephony.getClass().getMethod((enabled ? "enable" : "disable") + "DataConnectivity");
            m.invoke(telephony);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}